package com.gwsdk.paysdk.manager;

import android.content.Context;
import android.util.Log;

import com.gwsdk.paysdk.bean.MqttInfo;
import com.gwsdk.paysdk.entity.UserLogin;
import com.gwsdk.paysdk.utils.AppStatusManager;

import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

public class GWMqttManager {

    private final static String TAG = "GWMqttManager";

    private Context context;
    private static GWMqttManager sharedClient;

    private final int qos = 0;
    private MqttAndroidClient mqttAndroidClient;
    private MqttConnectOptions mMqttConnectOptions;
    private ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);

    private static final String TOPIC_BOSS = "boss";
    private static final String TOPIC_ROOM = "room";

    public static GWMqttManager getInstance() {
        if (sharedClient == null) {
            synchronized (GWMqttManager.class) {
                if (sharedClient == null) {
                    sharedClient = new GWMqttManager();
                }
            }
        }
        return sharedClient;
    }

    public void init(Context context){
        this.context = context;
    }

    public void initMqtt(){

        UserLogin user = AppStatusManager.getInstance().userLogin;

        String clientId = "android-" + user.getUserId() + "-";

        MqttInfo mqttInfo = AppStatusManager.getInstance().mqtt;
        String host = "tcp://"+mqttInfo.ip+":"+mqttInfo.port;

        if (mqttAndroidClient == null) {
            mqttAndroidClient = new MqttAndroidClient(context, host, clientId);
            mqttAndroidClient.setCallback(mqttCallback);
        }
        mMqttConnectOptions = new MqttConnectOptions();
        mMqttConnectOptions.setCleanSession(true); //设置是否清除缓存
        mMqttConnectOptions.setConnectionTimeout(10); //设置超时时间，单位：秒
        mMqttConnectOptions.setKeepAliveInterval(10); //设置心跳包发送间隔，单位：秒
        doClientConnection();
    }
    private void doClientConnection() {
        Log.e("doClientConnection", "doClientConnection");
        try {
            mqttAndroidClient.connect(mMqttConnectOptions, context, iMqttActionListener);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //订阅主题的回调
    private MqttCallback mqttCallback = new MqttCallback() {

        @Override
        public void messageArrived(String topic, MqttMessage message) throws Exception {
            Log.e(TAG, "收到的消息 主题：" + topic + "  收到的消息：" + message.toString());

        }
        @Override
        public void deliveryComplete(IMqttDeliveryToken arg0) {

        }

        @Override
        public void connectionLost(Throwable arg0) {
            Log.e(TAG, "链接状态：链接断开");
            doClientConnection();
        }
    };



    //MQTT是否连接成功的监听
    private IMqttActionListener iMqttActionListener = new IMqttActionListener() {

        @Override
        public void onSuccess(IMqttToken arg0) {
            Log.e(TAG, "链接状态成功");
        }

        @Override
        public void onFailure(IMqttToken arg0, Throwable arg1) {
            arg1.printStackTrace();
            Log.e(TAG, "链接状态失败");
            if (arg1 instanceof MqttException) {
                MqttException mqttException = (MqttException) arg1;
                mqttException.printStackTrace();
                Log.e(TAG, "链接状态失败" + mqttException.getMessage());
            }
        }
    };

    public boolean isAlreadyConnected() {
        if (mqttAndroidClient != null) {
            try {
                return mqttAndroidClient.isConnected();
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        } else {
            return false;
        }
    }
}
